import { setStore } from '@material/helpers';
import { MessagePluginManager } from '.';
import { Message, MessageEvent } from '..';
import { isEndChuns } from '../dispose';
import { ErrorType, MessageInfo, SendApiResult, SendParams } from '../type';

export class AiNewSessionPlugin implements MessagePluginManager {
    msgId: string;
    interrupt: boolean;
    name: string;
    cancelMessageId: string;
    lastMessageId: string;

    constructor() {
        this.name = 'AiNewSessionPlugin';
        this.msgId = '';
        this.cancelMessageId = '';
        this.interrupt = false;
        this.lastMessageId = '';
    }
    stopChatNext(context: Message) {
        if (!context) {
            return;
        }
        if (!this.msgId) {
            context.triggerHook(MessageEvent.Error, {
                type: ErrorType.LOGIC,
                message: '为获取到消息ID，无法进行超时拦截'
            });
            return;
        }
        this.interrupt = true;
        this.cancelMessageId = this.msgId;
        return context.stopChat(this.msgId);
    }

    async beforeSendAsync(params: SendParams, context: Message) {
        const { MsgType: msgType, Event: event } = params;
        if (msgType === 'event' && event === 'reset_ai_chat') {
            const res = await this.stopChatNext(context);
            const [err, data] = [...(res || [])];
            if (err) {
                context.triggerHook(MessageEvent.Error, {
                    type: ErrorType.LOGIC,
                    message: `为获取到消息ID，无法进行超时拦截,${data}`
                });
            }
        }
        if (msgType !== 'event' && !['cancel_answer', 'reset_ai_chat'].includes(event)) {
            this.cancelMessageId = '';
            this.lastMessageId = '';
        }

        return params;
    }
    afterSend(response: [0 | 1, SendApiResult]) {
        const [err, data] = response;
        if (!err && data) {
            this.msgId = this.msgId ? this.msgId : data.content || '';
        }
        return response;
    }

    beforeReceive(info: MessageInfo) {
        if (info.FromType === 'user') {
            this.msgId = info.MsgId || info.ExtInfo?.msg_id || this.msgId || '';
        }
        const endType = isEndChuns(info);
        if (info && endType === 'cancel_answer') {
            return false;
        }
        if (this.cancelMessageId && this.cancelMessageId === info.ExtInfo?.msg_id) {
            return false;
        }
        if (
            info &&
            info.FromType === 'user' &&
            ['cancel_answer', 'reset_ai_chat'].includes(info.Event)
        ) {
            this.interrupt = false;
            if (!this.lastMessageId) {
                this.lastMessageId = info.MsgId;
                setStore('AI_Message_Last_id', this.cancelMessageId);
            }

            return false;
        }
        if (info && this.interrupt) {
            return false;
        }
        return info;
    }
    beforeDestroy() {
        this.interrupt = false;
        this.msgId = '';
    }
}
